﻿/*******************************************************************************
#                    ADMUserBroker.cs
#  Comment:
#
#  Current Version: V1.0
#  Author: 
#
#  History List:
#  V1.0    Created by Onions@2009-8-21 13:08:14
#
#******************************************************************************/
#region Usings
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using SYS.Basic;

using ExpertMIS.Brokers;
using ExpertMIS.Entities;
using System.Collections;
#endregion

namespace ExpertMIS.Brokers
{
    public class ADMUserBroker : ExpertMISBaseBroker
    {
        #region Private Methods

        private object UpdateADMUserEntity(IEntity entity)
        {
            return SqlMap.Update("UpdateADMUserEntity", entity);
        }

        private object InsertADMUserEntity(IEntity entity)
        {
            ADMUserEntity newEntity = entity as ADMUserEntity;
            newEntity.Password = SYS.Common.EncryptHelper.MD5Encrypt(newEntity.Password);
            return SqlMap.Insert("InsertADMUserEntity", newEntity);
        }

        private object DeleteADMUserEntity(IEntity entity)
        {
            return SqlMap.Delete("DeleteADMUserEntity", entity);
        }

       

        #endregion

        #region Override Methods

        protected override IEntity ProcessGetEntity(System.Collections.Hashtable keys)
        {
            if (!keys.Contains("OID")) throw new Exception("invalid request parameters.");
            return SqlMap.QueryForObject<IEntity>("SelectADMUserEntityByOID", keys["OID"] as string);
        }

        protected override bool ProcessSaveEntity(IEntity entity, Hashtable request)
        {
            if (entity.EntityState == EntityState.New)
            {
                InsertADMUserEntity(entity);
                entity.EntityState = EntityState.Old;
            }
            else
            {
                UpdateADMUserEntity(entity);
            }

            return true;
        }

        protected override IEntity ProcessNewEntity()
        {
            ADMUserEntity entity = new ADMUserEntity();

            // initial entity object

            return entity;
        }

        protected override bool ProcessRemoveEntity(IEntity entity, Hashtable request)
        {
            try
            {
                DeleteADMUserEntity(entity);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="OID">用户ID</param>
        /// <param name="newPwd">新密码</param>
        /// <returns>更改密码是否成功</returns>
        public bool ChangePassword(string OID, string newPwd)
        {
            // 判断输入参数是否有效
            if (string.IsNullOrEmpty(OID) || string.IsNullOrEmpty(newPwd))
            {
                return false;
            }


            ADMUserEntity entity = GetEntityByOID(OID);
            if (entity == null)
            {
                return false;
            }
            entity.Password = SYS.Common.EncryptHelper.MD5Encrypt(newPwd);
        
            UpdateADMUserEntity(entity);
            return true; 
        }

        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="OID">用户ID</param>
        /// <param name="newPwd">新密码</param>
        /// <returns>重置密码操作是否成功</returns>
        public bool ResetPassword(string OID, ref string newPwd) 
        {
            if(string.IsNullOrEmpty(OID))
            {
                return false;
            }

            try
            {
                ADMUserEntity userEntity = GetEntityByOID(OID);
                if (userEntity == null)
                {
                    return false;
                }
                // 默认用户密码放在系统环境变量中
                SYS.Common.Broker.EnvironmentBroker broker = new SYS.Common.Broker.EnvironmentBroker();
                SYS.Common.Broker.EnvironmentEntity evEntity = broker.GetEnvironmentValue("DefaultUserPassword", false);
                if (evEntity == null || evEntity.Value.Contains("$"))
                {
                    //随机生成
                    Random rand = new Random();
                    newPwd = userEntity.Name + rand.Next(1000);
                }
                else
                {
                    newPwd = evEntity.Value;
                    return ChangePassword(OID, newPwd);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 根据用户ID获取用户实体
        /// </summary>
        /// <param name="OID">用户ID</param>
        /// <returns></returns>
        public ADMUserEntity GetEntityByOID(string OID)
        {
            if (string.IsNullOrEmpty(OID))
            {
                return null;
            }

            Hashtable hsQuery = new Hashtable();
            hsQuery.Add("OID", OID);
            return GetEntity(hsQuery) as ADMUserEntity;
        }

        /// <summary>
        /// 注册用户信息：
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="errorInfo"></param>
        /// <returns>
        ///  成功：errorInfo则返回当前ID，
        ///  失败：errorInfo则返回错误信息
        /// </returns>
        public bool RegisterUser(IEntity entity, ref string errorInfo)
        {
            ADMUserEntity userEntity = entity as ADMUserEntity;
            if( userEntity == null)
            {
                  errorInfo = "传入用户注册对象无效！";
                return false;
            }
            
            if(string.IsNullOrEmpty(userEntity.Account))
            {
                errorInfo = "传入用户注册对象帐号无效！";
                return false;
            }

            try
            {
                // 判断entity是否有重名帐号
                IEntity obj = GetUserByAccount(userEntity.Account);
                if (obj != null)
                {
                    errorInfo = "当前帐号已存在！";
                    return false;
                }

                errorInfo = InsertADMUserEntity(userEntity).ToString();
                return true;
            }
            catch(Exception ex)
            {
                // 提供详细日志信息
                errorInfo = "系统发生异常，详细信息：" + ex.Message;
                return false;
            }
        }

        public IList<ADMUserEntity> GetAllUsers()
        {
            return SqlMap.QueryForList<ADMUserEntity>("SelectAllUsers", null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool VeritifyUser(string account, string password)
        {
            try
            {
                int count = GetVeritifyUser(account, password);

                if (count == 0 || count > 1)
                {
                    return false;
                }
                else
                {
                    return true;
                }

                //ADMUserEntity entity = GetUserByAccount(account);
                //if (entity == null)
                //{
                //    return false;
                //}

                //string encryptPassword = SYS.Common.EncryptHelper.MD5Encrypt(password);
                //StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                //if (0 == comparer.Compare(encryptPassword, entity.Password))
                //{
                //    return true;
                //}
                //else
                //{
                //    return false;
                //}
            }
            catch
            {
                return false;
            }
        }

        private int GetVeritifyUser(string account, string password)
        {
            string encryptPassword = SYS.Common.EncryptHelper.MD5Encrypt(password);

            Hashtable hsQuery = new Hashtable();
            hsQuery.Add("account", account);
            hsQuery.Add("password", encryptPassword);
            return (int)SqlMap.QueryForObject("SelectVeritifyUser", hsQuery); 
        }

        /// <summary>
        /// 获取所有未审核用户列表
        /// </summary>
        /// <returns></returns>
        public IList<ADMUserEntity> GetAllUnPassedUser()
        {
            return SqlMap.QueryForList<ADMUserEntity>("SelectAllUnPassedUser", null);
        }

        /// <summary>
        /// 获取未审核用户总数
        /// </summary>
        /// <returns></returns>
        public int GetUnPassedUserCount()
        {
            return (int)SqlMap.QueryForObject("SelectUnPassedUserCount", null);
        }

        /// <summary>
        /// 获取注册用户总数
        /// </summary>
        /// <returns></returns>
        public int GetRegisterUserCount()
        {
            return (int)SqlMap.QueryForObject("SelectRegisterUserCount", null); 
        }

        /// <summary>
        /// 获取专家总数
        /// </summary>
        /// <returns></returns>
        public object GetExpertCount()
        {
            return (int)SqlMap.QueryForObject("SelectExpertCount", null);
        }

        /// <summary>
        /// 通过帐号获取用户对象
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public ADMUserEntity GetUserByAccount(string account)
        {
            return SqlMap.QueryForObject<ADMUserEntity>("SelectUserbyAccount", account);
        }

        /// <summary>
        /// 注册匿名用户
        /// </summary>
        /// <param name="entity">匿名用户实体</param>
        /// <param name="newOID">新ID</param>
        /// <returns></returns>
        public bool RegisterAnonymousUser(ADMUserEntity entity, ref string newOID)
        {
            if (entity == null)
            {
                return false;
            }

            try
            {
                entity.Account = Guid.NewGuid().ToString();
                entity.Password = Guid.NewGuid().ToString();
                entity.IsAdmin = false;
                entity.IsExpert = false;
                entity.IsPassed = true;
                entity.Enable = false;
                entity.Stamp = DateTime.Now;

                InsertADMUserEntity(entity);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取所有专家用户
        /// </summary>
        /// <returns></returns>
        public IList<ADMUserEntity> GetAllExpertUsers()
        {
            return SqlMap.QueryForList<ADMUserEntity>("SelectAllExpertUsers", null);
        }

        #endregion
    }
}